//
//  FirCirMailNewsdb.m
//  tcpoctest
//
//  Created by apple on 13-5-2.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "FirCirMailNewsdb.h"
#import "FirCirNewsMailDataSource.h"
#import "FirCirPersonDataSource.h"

@implementation FirCirMailNewsdb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists fircirnewsmail(newsid text,\
mail text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    [[DataControl shareControl].fcnewsmailDS DelAll];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString    *strsql = [NSString stringWithFormat:@"select * from fircirnewsmail"];
    FMResultSet *s = [db executeQuery:strsql];
    
    while ([s next]) {
        [[DataControl shareControl].fcnewsmailDS AddMail:[s stringForColumn:@"mail"]
                                              withNewsID:[s stringForColumn:@"newsid"]];
    }
    
    [[DataControl shareControl].fcPersonDS DelAllDic];
    
    strsql = [NSString stringWithFormat:@"select mail from  fircirnewsmail"];
    
    s = [db executeQuery:strsql];
    
    while ([s next]) {
        
        NSString *mail = [s stringForColumn:@"mail"];
        
        strsql = [NSString stringWithFormat:@"select newsid from fircirnewsmail \
where mail = '%@'",mail];
        
        FMResultSet *ss = [db executeQuery:strsql];
        
        while ([ss next]) {
            [[DataControl shareControl].fcPersonDS insertNewsIDToMail:mail
                                                           withNewsID:[ss stringForColumn:@"newsid"]
                                                            withOrder:ORDER_ASC];
        }
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertNewMail:(NSString *)newid withMail:(NSString *)strmail
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString    *strsql = [NSString stringWithFormat:@"select * from fircirnewsmail \
where newsid = '%@'",newid];
    FMResultSet *s = [db executeQuery:strsql];
    
    if (![s next]) {
        strsql = [NSString stringWithFormat:@"insert into fircirnewsmail \
(newsid,mail) values('%@','%@')"
                  ,newid
                  ,strmail];
        
        [db executeUpdate:strsql];
        
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);

}

-(void)delMailByNewId:(NSString *)newid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString    *strsql = [NSString stringWithFormat:@"delete FROM fircirnewsmail WHERE newsid='%@'",newid];
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
